<template>
  <div class="favorites-container">
    <!-- 导航栏 -->
    <div class="navbar">
      <router-link to="/profile" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </router-link>
      <div class="navbar-title">我的收藏</div>
      <div class="navbar-actions">
        <i class="fas fa-ellipsis-v"></i>
      </div>
    </div>

    <!-- 分类选择 -->
    <div class="category-tabs">
      <div 
        v-for="(category, index) in categories" 
        :key="index"
        :class="['category-tab', selectedCategory === category.type ? 'active' : '']"
        @click="selectCategory(category.type)"
      >
        <i :class="category.icon"></i>
        <span>{{ category.name }}</span>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!currentFavorites.length" class="empty-state">
      <div class="empty-icon">
        <i class="far fa-heart"></i>
      </div>
      <div class="empty-text">暂无收藏内容</div>
      <div class="empty-desc">快去收藏一些{{ getCategoryName(selectedCategory) }}吧</div>
    </div>

    <!-- 收藏列表 -->
    <div v-else class="favorites-content">
      <!-- 商品收藏 -->
      <div v-if="selectedCategory === 'product'" class="product-favorites">
        <div class="favorites-grid">
          <div 
            v-for="item in currentFavorites" 
            :key="item.favoriteId"
            class="favorite-item product-item"
          >
            <router-link :to="`/product/${item.id || item.productId}`" class="item-link">
              <img :src="item.mainImage" :alt="item.name" class="item-image">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-price">¥{{ item.price }}</div>
                <div class="item-store">{{ item.storeName }}</div>
              </div>
            </router-link>
            <button class="remove-btn" @click="removeFavorite(item.favoriteId)">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 视频收藏 -->
      <div v-else-if="selectedCategory === 'video'" class="video-favorites">
        <div class="favorites-list">
          <div 
            v-for="item in currentFavorites" 
            :key="item.favoriteId"
            class="favorite-item video-item"
          >
            <router-link :to="`/videoPlayer/${item.videoId}`" class="item-link">
              <div class="video-thumbnail">
                <img :src="item.coverImage" :alt="item.title" class="item-image">
                <div class="video-duration">{{ formatDuration(item.duration) }}</div>
                <div class="play-icon">
                  <i class="fas fa-play"></i>
                </div>
              </div>
              <div class="item-info">
                <div class="item-title">{{ item.title }}</div>
                <div class="item-meta">
                  <span class="author">{{ item.authorName }}</span>
                  <span class="views">{{ formatViews(item.views) }}次观看</span>
                </div>
                <div class="item-desc">{{ item.description }}</div>
              </div>
            </router-link>
            <button class="remove-btn" @click="removeFavorite(item.favoriteId)">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 商店收藏 -->
      <div v-else-if="selectedCategory === 'store'" class="store-favorites">
        <div class="favorites-list">
          <div 
            v-for="item in currentFavorites" 
            :key="item.favoriteId"
            class="favorite-item store-item"
          >
            <router-link :to="`/store/${item.storeId}`" class="item-link">
              <img :src="item.coverImage" :alt="item.name" class="store-logo">
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-meta">
                  <span class="rating">评分 {{ item.rating }}</span>
                  <span class="followers">{{ item.followerCount }}人关注</span>
                </div>
                <div class="item-desc">{{ item.description }}</div>
              </div>
            </router-link>
            <button class="remove-btn" @click="removeFavorite(item.favoriteId)">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/network/api'
import { showDialog } from 'vant'

export default {
  name: 'Favorites',
  data() {
    return {
      loading: false,
      selectedCategory: 'product',
      favorites: {
        product: [],
        video: [],
        store: []
      },
      categories: [
        { type: 'product', name: '商品', icon: 'fas fa-shopping-bag' },
        { type: 'video', name: '视频', icon: 'fas fa-video' },
        { type: 'store', name: '商店', icon: 'fas fa-store' }
      ]
    }
  },
  computed: {
    currentFavorites() {
      return this.favorites[this.selectedCategory] || []
    },
    favoritesCount() {
      return {
        product: this.favorites.product.length,
        video: this.favorites.video.length,
        store: this.favorites.store.length
      }
    }
  },
  methods: {
    async fetchFavorites(type) {
      try {
        this.loading = true
        const response = await api.getFavorites(type)
        
        console.log(`获取${type}收藏响应:`, response)
        
        if (response && response.code === 100) {
          this.favorites[type] = response.data || []
          console.log(`${type}收藏数据:`, this.favorites[type])
        } else {
          console.error('获取收藏失败:', response?.message)
          this.favorites[type] = []
        }
      } catch (error) {
        console.error('获取收藏失败:', error)
        this.favorites[type] = []
      } finally {
        this.loading = false
      }
    },

    async selectCategory(type) {
      this.selectedCategory = type
      if (!this.favorites[type].length) {
        await this.fetchFavorites(type)
      }
    },

    async removeFavorite(favoriteId) {
      try {
        // 根据收藏类型获取对应的ID字段
        let id;
        const item = this.favorites[this.selectedCategory].find(
          item => item.favoriteId === favoriteId
        );
        
        if (!item) {
          console.error('未找到收藏项:', favoriteId)
          return
        }
        
        // 根据类型获取对应的ID
        switch (this.selectedCategory) {
          case 'product':
            id = item.id || item.productId
            break
          case 'video':
            id = item.videoId
            break
          case 'store':
            id = item.storeId
            break
          default:
            console.error('未知的收藏类型:', this.selectedCategory)
            return
        }
        
        // 调用API取消收藏
        const response = await api.removeFavorite(this.selectedCategory, id)
        
        // 检查响应状态
        if (response && response.code === 100) {
          // 从当前列表中移除
          const index = this.favorites[this.selectedCategory].findIndex(
            item => item.favoriteId === favoriteId
          )
          if (index > -1) {
            this.favorites[this.selectedCategory].splice(index, 1)
          }

          this.$toast?.success('取消收藏成功')
        } else {
          // 处理特定错误情况
          showDialog({
            title: '提示',
            message: response?.message || '取消收藏失败，请重试',
          })
        }
      } catch (error) {
        console.error('取消收藏失败:', error)

        // 检查错误响应格式
        if (error.response && error.response.data) {
          showDialog({
            title: '提示',
            message: error.response.data.message || '取消收藏失败，请重试',
          })
        } else {
          this.$toast?.error('取消收藏失败，请重试')
        }
      }
    },

    getCategoryName(type) {
      const category = this.categories.find(cat => cat.type === type)
      return category ? category.name : ''
    },

    formatDuration(seconds) {
      if (!seconds) return '00:00'
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
    },

    formatViews(views) {
      if (!views) return '0'
      if (views >= 10000) {
        return (views / 10000).toFixed(1) + '万'
      }
      return views.toString()
    }
  },
  async created() {
    await this.fetchFavorites(this.selectedCategory)
  }
}
</script>

<style scoped>
.favorites-container {
  min-height: 100vh;
  background-color: #f8fafc;
  padding-bottom: 20px;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-back {
  color: #4a5568;
  text-decoration: none;
  font-size: 18px;
  padding: 5px;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  flex: 1;
  text-align: center;
}

.navbar-actions {
  width: 30px;
  text-align: right;
}

.navbar-actions i {
  color: #4a5568;
  font-size: 18px;
  padding: 5px;
  cursor: pointer;
}

.category-tabs {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 0 15px;
}

.category-tab {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  color: #718096;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.category-tab.active {
  color: #3490dc;
  font-weight: 500;
}

.category-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20%;
  right: 20%;
  height: 2px;
  background-color: #3490dc;
}

.category-tab i {
  font-size: 20px;
  margin-bottom: 5px;
}

.category-tab span {
  font-size: 12px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #a0aec0;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3490dc;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #a0aec0;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #cbd5e0;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 10px;
  color: #718096;
}

.empty-desc {
  font-size: 14px;
  color: #a0aec0;
}

.favorites-content {
  padding: 15px;
}

/* 商品收藏样式 */
.favorites-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.product-item {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  position: relative;
}

.product-item .item-link {
  text-decoration: none;
  color: inherit;
  display: block;
}

.product-item .item-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.product-item .item-info {
  padding: 10px;
}

.product-item .item-name {
  font-size: 14px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 40px;
}

.product-item .item-price {
  color: #e53e3e;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.product-item .item-store {
  font-size: 12px;
  color: #718096;
}

/* 视频收藏样式 */
.favorites-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.video-item {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  position: relative;
}

.video-item .item-link {
  text-decoration: none;
  color: inherit;
  display: flex;
  padding: 15px;
}

.video-thumbnail {
  position: relative;
  width: 150px !important;
  height: 100px !important;
  margin-right: 15px;
  flex-shrink: 0;
}

.video-thumbnail .item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.video-duration {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 10px;
  padding: 2px 4px;
  border-radius: 2px;
}

.play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 30px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
}

.video-item .item-info {
  flex: 1;
}

.video-item .item-title {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 48px;
}

.video-item .item-meta {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #718096;
}

.video-item .author {
  margin-right: 10px;
}

.video-item .item-desc {
  font-size: 12px;
  color: #a0aec0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 32px;
}

/* 商店收藏样式 */
.store-item {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  position: relative;
}

.store-item .item-link {
  text-decoration: none;
  color: inherit;
  display: flex;
  padding: 15px;
}

.store-item .store-logo {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 15px;
  flex-shrink: 0;
}

.store-item .item-info {
  flex: 1;
}

.store-item .item-name {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 8px;
}

.store-item .item-meta {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 12px;
  color: #718096;
}

.store-item .rating {
  margin-right: 10px;
}

.store-item .item-desc {
  font-size: 12px;
  color: #a0aec0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  height: 32px;
}

/* 删除按钮 */
.remove-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 30px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
  z-index: 10;
}

.remove-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.remove-btn i {
  font-size: 12px;
}

@media (max-width: 640px) {
  .favorites-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }
  
  .video-thumbnail {
    width: 100px;
    height: 70px;
  }
  
  .store-logo {
    width: 50px;
    height: 50px;
  }
}

@media (min-width: 768px) {
  .favorites-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (min-width: 1024px) {
  .favorites-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}
</style>
